package cn.xz.tipsum.utils;


import static cn.xz.tipsum.bean.MyBeanKt.ERROR_CODE;
import static cn.xz.tipsum.bean.MyBeanKt.GET_MSG;
import android.app.Notification;
import android.content.ComponentName;
import android.os.Build;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import cn.xz.tipsum.base.BaseApplication;
import cn.xz.tipsum.bean.EventBusMessage;
import cn.xz.tipsum.bean.MyBean;
import cn.xz.tipsum.dialog.ErrorDialog;

public class MyNotificationListenerService extends NotificationListenerService {

    //微信
    static String WX = "com.tencent.mm";
    //支付宝
    static String ZFB = "com.eg.android.AlipayGphone";

    //来消息监听
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Notification notification = sbn.getNotification();
        if (notification == null) {
            return;
        }
        Bundle extras = notification.extras;
        if (extras != null) {
            try {
                //包名
                String pkg = sbn.getPackageName();
                // 获取通知标题
                String title = extras.getString(Notification.EXTRA_TITLE, "");
                // 获取通知内容
                String content = extras.getString(Notification.EXTRA_TEXT, "");
                // 获取通知时间
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                Date curDate = new Date(sbn.getPostTime());
                String postTime = formatter.format(curDate);
                //Toast.makeText(BaseApplication.Companion.getContext(),String.format("包：%s，标：%s，内：%s", pkg, title, content),Toast.LENGTH_LONG).show();
                Log.e("接收消息", String.format("收到通知，包名：%s，标题：%s，内容：%s,时间：%s", pkg, title, content,postTime));
                //处理
                processOnReceive(pkg, title, content,postTime);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 消息来时处理
     */
    public static void processOnReceive(String pkg, String title, String content,String postTime) {
        if (ZFB.equals(pkg)) {
            try {
                //支付宝
                if (checkMsgValid(title,content,"alipay")) {
                    String mC = parseMoney(title);
                    if (mC == null){
                        mC = parseMoney(content);
                    }
                    if (mC == null){
                        mC = parseMoney1(title);
                    }
                    if (mC == null){
                        mC = parseMoney1(content);
                    }
                    if (mC == null){
                        mC = parseMoney2(title);
                    }
                    if (mC == null){
                        mC = parseMoney2(content);
                    }
                    if (mC == null){
                        mC = parseMoney3(title);
                    }
                    if (mC == null){
                        mC = parseMoney3(content);
                    }
                    if (mC == null){
                        mC = parseMoney4(title);
                    }
                    if (mC == null){
                        mC = parseMoney4(content);
                    }
                    if (mC == null){
                        mC = parseMoney5(title);
                    }
                    if (mC == null){
                        mC = parseMoney5(content);
                    }
                    if (mC == null){
                        mC = parseMoney6(title);
                    }
                    if (mC == null){
                        mC = parseMoney6(content);
                    }
                    if (mC == null){
                        mC = parseMoney7(title);
                    }
                    if (mC == null){
                        mC = parseMoney7(content);
                    }
                    Log.e("支付宝到账", "processOnReceive: 支付宝收款---" + mC);

                    MyBean myBean = new MyBean("Z",mC,postTime);
                    EventBusUtils.INSTANCE.postEvent(new EventBusMessage(GET_MSG,myBean));
                }
            }catch (Exception e){
                e.printStackTrace();
                Toast.makeText(BaseApplication.Companion.getContext(), "title:" + title + "，content:" + content,Toast.LENGTH_LONG).show();
                //EventBusUtils.INSTANCE.postEvent(new EventBusMessage(ERROR_CODE,"报错信息:\ntitle:" + title + "\ncontent:" + content));

            }
        } else if (WX.equals(pkg)) {
            try {
                //微信
                if (checkMsgValid(title, content, "wxpay")) {
                    String mC = parseMoney(title);
                    if (mC == null){
                        mC = parseMoney(content);
                    }
                    if (mC == null){
                        mC = parseMoney1(title);
                    }
                    if (mC == null){
                        mC = parseMoney1(content);
                    }
                    if (mC == null){
                        mC = parseMoney2(title);
                    }
                    if (mC == null){
                        mC = parseMoney2(content);
                    }
                    if (mC == null){
                        mC = parseMoney3(title);
                    }
                    if (mC == null){
                        mC = parseMoney3(content);
                    }
                    if (mC == null){
                        mC = parseMoney4(title);
                    }
                    if (mC == null){
                        mC = parseMoney4(content);
                    }
                    if (mC == null){
                        mC = parseMoney5(title);
                    }
                    if (mC == null){
                        mC = parseMoney5(content);
                    }
                    if (mC == null){
                        mC = parseMoney6(title);
                    }
                    if (mC == null){
                        mC = parseMoney6(content);
                    }
                    if (mC == null){
                        mC = parseMoney7(title);
                    }
                    if (mC == null){
                        mC = parseMoney7(content);
                    }
                    Log.e("微信到账", "processOnReceive: 微信收款---" + mC);

                    MyBean myBean = new MyBean("V",mC,postTime);
                    EventBusUtils.INSTANCE.postEvent(new EventBusMessage(GET_MSG,myBean));
                }
            }catch (Exception e){
                e.printStackTrace();
                Toast.makeText(BaseApplication.Companion.getContext(), "title:" + title + "，content:" + content,Toast.LENGTH_LONG).show();
                //EventBusUtils.INSTANCE.postEvent(new EventBusMessage(ERROR_CODE,"报错信息:\ntitle:" + title + "\ncontent:" + content));
            }
        }
    }

    /**
     * 解析内容字符串，提取金额
     */
    public static String parseMoney(String content) {
        try {
            Pattern pattern = Pattern.compile("收款(([1-9]\\d*)|0)(\\.(\\d){0,2})?元");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String tmp = matcher.group();
                Pattern patternnum = Pattern.compile("(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
                Matcher matchernum = patternnum.matcher(tmp);
                if (matchernum.find())
                    return matchernum.group();
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String parseMoney1(String content) {
        try {
            Pattern pattern = Pattern.compile("到账(([1-9]\\d*)|0)(\\.(\\d){0,2})?元");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String tmp = matcher.group();
                Pattern patternnum = Pattern.compile("(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
                Matcher matchernum = patternnum.matcher(tmp);
                if (matchernum.find())
                    return matchernum.group();
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String parseMoney2(String content) {
        try {
            Pattern pattern = Pattern.compile("收款(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String tmp = matcher.group();
                Pattern patternnum = Pattern.compile("(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
                Matcher matchernum = patternnum.matcher(tmp);
                if (matchernum.find())
                    return matchernum.group();
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String parseMoney3(String content) {
        try {
            Pattern pattern = Pattern.compile("到账(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String tmp = matcher.group();
                Pattern patternnum = Pattern.compile("(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
                Matcher matchernum = patternnum.matcher(tmp);
                if (matchernum.find())
                    return matchernum.group();
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    public static String parseMoney4(String content) {
        try {
            Pattern pattern = Pattern.compile("收款¥(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String tmp = matcher.group();
                Pattern patternnum = Pattern.compile("(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
                Matcher matchernum = patternnum.matcher(tmp);
                if (matchernum.find())
                    return matchernum.group();
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String parseMoney5(String content) {
        try {
            Pattern pattern = Pattern.compile("到账¥(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String tmp = matcher.group();
                Pattern patternnum = Pattern.compile("(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
                Matcher matchernum = patternnum.matcher(tmp);
                if (matchernum.find())
                    return matchernum.group();
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String parseMoney6(String content) {
        try {
            Pattern pattern = Pattern.compile("收款¥(([1-9]\\d*)|0)(\\.(\\d){0,2})?元");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String tmp = matcher.group();
                Pattern patternnum = Pattern.compile("(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
                Matcher matchernum = patternnum.matcher(tmp);
                if (matchernum.find())
                    return matchernum.group();
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String parseMoney7(String content) {
        try {
            Pattern pattern = Pattern.compile("到账¥(([1-9]\\d*)|0)(\\.(\\d){0,2})?元");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String tmp = matcher.group();
                Pattern patternnum = Pattern.compile("(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
                Matcher matchernum = patternnum.matcher(tmp);
                if (matchernum.find())
                    return matchernum.group();
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 验证消息的合法性，防止非官方消息被处理
     */
    public static boolean checkMsgValid(String title, String content, String gateway) {
        try {
            if ("wxpay".equals(gateway)) {
                //微信支付的消息格式
                //1条：标题：微信支付，内容：微信支付收款0.01元(朋友到店)
                //多条：标题：微信支付，内容：[4条]微信支付: 微信支付收款1.01元(朋友到店)
            /*Pattern pattern = Pattern.compile("^((\\[\\+?\\d+条])?微信支付:|微信支付收款)");
            Matcher matcher = pattern.matcher(content);
            return "微信支付".equals(title) && matcher.find();*/
                return title.contains("收款") || title.contains("到账")  || content.contains("收款") || content.contains("到账");
            } else if ("alipay".equals(gateway)) {
                //支付宝的消息格式，标题：支付宝通知，内容：支付宝成功收款1.00元。
                return title.contains("收款") || title.contains("到账") || content.contains("收款") || content.contains("到账");
            }
            return false;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 监听断开
     */
    @Override
    public void onListenerDisconnected() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 通知侦听器断开连接 - 请求重新绑定
            Log.e("收到--","监听断开");
            requestRebind(new ComponentName(this, NotificationListenerService.class));
        }
    }
}
